package server;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Optional;

public class RequestProcessor extends Thread {

    private Socket socket;

    private List<Mapper> mapperList;

    public RequestProcessor(Socket socket, List<Mapper> mapperList) {
        this.socket = socket;
        this.mapperList = mapperList;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            String requestUrl = request.getUrl();
            // 静态资源处理
            if (mapperList == null || mapperList.size() == 0) {
                response.outputHtml(request.getUrl());
            } else {
                Optional<Mapper> mapperOptional = mapperList.stream()
                        .filter(mapper -> requestUrl.equals(mapper.getUrlPattern())).findFirst();
                boolean present = mapperOptional.isPresent();
                if (!present) {
                    response.outputHtml(request.getUrl());
                    return;
                } else {
                    HttpServlet httpServlet = mapperOptional.get().getHttpServlet();
                    httpServlet.service(request, response);
                }
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
